﻿using PwjCy.Lite.Common;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace PwjCy.Lite.Core
{
    /// <summary>
    /// 服务容器
    /// </summary>
    public class ServiceContainer : IServiceContainer, IServiceProvider
    {
        /// <summary>
        /// 获取服务类型
        /// </summary>
        /// <typeparam name="TService">服务接口类型</typeparam>
        /// <returns></returns>
        public TService GetService<TService>()
        {
            return this.GetService<TService>(true);
        }
        /// <summary>
        /// 获取服务类型
        /// </summary>
        /// <typeparam name="TService">服务接口类型</typeparam>
        /// <param name="throwExceptionIfNotFound">是否抛出异常</param>
        /// <returns></returns>
        public TService GetService<TService>(bool throwExceptionIfNotFound)
        {
            Type t = typeof(TService);
            return (TService)this.GetService(t, throwExceptionIfNotFound);
        }
        /// <summary>
        /// 获取服务类型
        /// </summary>
        /// <param name="serviceType">服务接口类型</param>
        /// <returns></returns>
        public object GetService(Type serviceType)
        {
            return GetService(serviceType, true);
        }
        /// <summary>
        /// 获取服务类型
        /// </summary>
        /// <param name="serviceType">服务接口类型</param>
        /// <param name="throwExceptionIfNotFound">是否抛出异常</param>
        /// <returns></returns>
        public object GetService(Type serviceType, bool throwExceptionIfNotFound)
        {
            object obj = HashCacheHelper.Instance.GetCache<object>(serviceType.FullName);
            if (!throwExceptionIfNotFound)
            {
                if (null == obj) return null;
                return obj;
            }
            if (null == obj)
            {
                throw new Exception("Not Found Services that Type is " + serviceType.FullName);
            }
            return obj;
        }
    }
}
